//
//  NearByViewController.m
//  ACSProduct
//
//  Created by gaurav on 09/10/11.
//  Copyright 2011 dhillon. All rights reserved.
//

#import "NearByViewController.h"


@implementation NearByViewController
@synthesize urls,downloads,arrayImageView;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
}

- (void) didFinishDownload:(NSNumber*)idx {
    //for(int i=0;i<[arrayImages count];i++)
    //{
    NSLog(@"imageget");
       
    UIImageView *viewImage = [arrayImageView objectAtIndex:[idx intValue]];
    viewImage.image = [UIImage imageWithData:[downloads dataAtIndex:[idx intValue]]];
    
    //}
    //    if([idx intValue]==0)
    //    {
    //    
    //        imageV1.image = [UIImage imageWithData:[downloads dataAtIndex:[idx intValue]]];
    //
    //    }
    //    if([idx intValue]==1)
    //    {
    //        
    //        imageV2.image = [UIImage imageWithData:[downloads dataAtIndex:[idx intValue]]];
    //        
    //    }
    //[arrayAlbums addObject:[[[downloads dataAsStringAtIndex: [idx intValue]] JSONValue]copy]];
	//NSLog(@"%d download: %@", [idx intValue], [downloads dataAsStringAtIndex: [idx intValue]]);
    
}

- (void) didFinishAllDownload {
    // [tableList reloadData];
}
- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark -Delegate viewToolPicker-

-(void)pressDoneForSel:(NSString *)stringSel withindex:(NSInteger)indexRow
{
    pickerDis.hidden = YES;
    radius = [[arrayDistanceFilter objectAtIndex:indexRow ]intValue];
    NSLog(@"----[[arrayDistanceFilter objectAtIndex:indexRow ]intValue]--------%d",[[arrayDistanceFilter objectAtIndex:indexRow ]intValue]);
    [self tableViewSettingWithRad:[[arrayDistanceFilter objectAtIndex:indexRow ]intValue]];

}


-(void)filterButtonClicked
{
    pickerDis.hidden = NO;
}
-(void)reloadData:(NSNotificationCenter*)notification
{
    [tableNearBy   reloadData];
}

- (void)viewWillAppear:(BOOL)animated
{
    if(kmsel == 0 && KMselect != 0)
    {
        [tableNearBy    reloadData];
        kmsel = 1;
    }
    else if(kmsel == 1 && KMselect !=1 )
    {
        [tableNearBy reloadData];
        kmsel = 0;
    }
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    //[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadData:) name:CHANGEMEASUNIT object:nil];

//    UIBarButtonItem *filterButton = [[UIBarButtonItem alloc] initWithTitle:@"Filter"
//                                                                    style:UIBarButtonItemStyleDone
//                                                                   target:self
//                                                                   action:@selector(filterButtonClicked)];
//    self.navigationItem.rightBarButtonItem = filterButton;
//    [filterButton release];
    tableNearBy.backgroundView = nil;
    tableNearBy.backgroundColor = [UIColor  clearColor];
    if (_refreshHeaderView == nil) {
		
		EGORefreshTableHeaderView *view = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - tableNearBy.bounds.size.height, self.view.frame.size.width, tableNearBy.bounds.size.height)];
        view.backgroundColor = [UIColor clearColor];
		view.delegate = self;
		[tableNearBy addSubview:view];
		_refreshHeaderView = view;
		[view release];
		
	}
    [[NSNotificationCenter  defaultCenter] addObserver:self
                                              selector:@selector(datareload:) 
                                                  name:KsReLOADDATAMETERRAN
                                                object:nil];
    
//    NSArray *arrayDistance = [NSArray arrayWithObjects:@"0-50",@"0-100",@"0-150",@"0-200",@"0-250", nil];
//    arrayDistanceFilter = [[NSMutableArray alloc] initWithArray:[NSArray arrayWithObjects:@"50",@"100",@"150",@"200",@"250", nil]];
//    
//    NSMutableArray *arrayDis = [[NSMutableArray alloc] initWithArray:arrayDistance];
//    
//    pickerDis = [[ViewPickerTool alloc] initWithFrame:CGRectMake(0, 0, 320, 194)];
//    [self.view addSubview:pickerDis];
//    [pickerDis setClient:self];
//    pickerDis.hidden = YES;
//    [pickerDis addTheElement:arrayDis];
    
    
    [self.navigationItem setTitle:@"Near By"];
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view 
                                              animated:YES];
    hud.labelText = @"Loading...";
    
    [self tableViewSettingWithRad:50];
   
    [self.navigationController.navigationBar setTintColor:[UIColor blackColor] ];
    
    
    
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

-(void)datareload:(NSNotification *)notification
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view 
                                              animated:YES];
    hud.labelText = @"Loading...";
    NSLog(@"••¶¶%s",__PRETTY_FUNCTION__);
    [self tableViewSettingWithRad:50];
}


-(void)tableViewSettingWithRad:(NSInteger)radius
{
    if([ModalController  getContforKey:KsSWITCHEDMETER] )
        radius = [[ModalController  getContforKey:RADSAVEDSAT] integerValue];
    else {
        radius = 1;
    }
    
    
    if(TESTING)
        radius = 20000;
    
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:URLDATA]];
    
    [request setRequestMethod:@"POST"];
    [request setPostValue:locationUser.strUserLat forKey:BASELAT];
    [request setPostValue:locationUser.strUserLong forKey:BASELONG];
    [request setPostValue:[NSString stringWithFormat:@"%d",radius] forKey:BASEDIS];
    [request setPostValue:@"" forKey:BASEIND];
    [request setPostValue:@"" forKey:BASECAT];
//    [request setPostValue:@"999999"  forKey:@"City"];

    [request setPostValue:@"" forKey:kSubCatId];
    
    [request setDelegate:self];
    
   
    
    [request startAsynchronous];
}

#define mark -ASIHTTP request delegates-


- (void)requestFinished:(ASIHTTPRequest *)request
{
    [self doneLoadingTableViewData];

    [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
    
    if(LOGOFF == 1) NSLog(@"I have got data------->>>>>%@",[request responseString]);
    
    NSDictionary *_xmlDictionaryData = [[XMLReader dictionaryForXMLData:[request responseData] error:nil] retain];
    
    if(LOGOFF == 1) NSLog(@"%@",_xmlDictionaryData);
    
    arrayNearBy = [[NSMutableArray alloc] init];
    
    if([[_xmlDictionaryData objectForKey:@"Lists"] objectForKey:@"List"])
    {
        if([[[_xmlDictionaryData objectForKey:@"Lists"] objectForKey:@"List"] isKindOfClass:[NSArray class]])
            arrayNearBy  = [[NSMutableArray alloc] initWithArray:[[_xmlDictionaryData objectForKey:@"Lists"] objectForKey:@"List"]];
        
        else
        {
            arrayNearBy = [[NSMutableArray alloc] init];
            [arrayNearBy addObject:[[_xmlDictionaryData objectForKey:@"Lists"] objectForKey:@"List"]];
        }
    }
    
    if(LOGOFF == 1) NSLog(@"arrayNearBy Connt=%d",[arrayNearBy count]);
    if([arrayNearBy count]==0)
    {
        lableNoNearBy.hidden = NO;
        tableNearBy.hidden = YES;
    }
    else
    {
        lableNoNearBy.hidden = YES;
        tableNearBy.hidden = NO;
        
        tableNearBy.delegate = self;
        tableNearBy.dataSource = self;        
    }
    [self assignInitialValue];
    [tableNearBy    reloadData];

}


- (void)requestFailed:(ASIHTTPRequest *)request
{
    [MBProgressHUD  hideHUDForView:self.navigationController.view animated:YES];
    [self doneLoadingTableViewData];

    [ModalController showTheAlertWithMsg:@"Error in network" withTitle:@"Failed" inController:self];        
}

#pragma mark -tableview code-
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 55;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	// The number of sections is based on the number of items in the data property list.
	return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{	
	return end-start;	
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{	
	
	CustomTableCell *cell = (CustomTableCell *)[tableView dequeueReusableCellWithIdentifier:@"CustomTableCell"];
	if(cell == nil) 
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomTableCell" owner:self options:nil];
        cell = (CustomTableCell *)[nib objectAtIndex:0];
        
        
        CAGradientLayer *gradient = [CAGradientLayer layer];
        gradient.frame = cell.bounds;
        
        CGColorRef topColor = [[UIColor whiteColor] CGColor];
        CGColorRef bottomColor = [[UIColor colorWithRed:0.80 green:.80 blue:.80 alpha:1.0] CGColor];
        gradient.colors = [NSArray arrayWithObjects:(id)topColor, (id)bottomColor, nil];
        
        [cell.layer insertSublayer:gradient atIndex:0];
    }
    
    //    cell.backgroundColor = COLORCELL
    
    arraySelect=[[NSMutableArray alloc]init];
    for(int i=start;i<end;i++)
    {
        [arraySelect addObject:[arrayNearBy objectAtIndex:i]];
    }
    
	[cell settitle:[[arraySelect objectAtIndex:indexPath.row] objectForKey:FIELDNAME]];
    //cell.subtitle.text = stringTitle;
    cell.subtitle.text = [NSString stringWithFormat:@"%@",[[arraySelect objectAtIndex:indexPath.row] objectForKey:kDealBanner]];
    [cell setCostLabelstr:[NSString stringWithFormat:@"£%@",[[arraySelect objectAtIndex:indexPath.row] objectForKey:FIELDCOST]]];
    cell.description.text = [NSString stringWithFormat:@"%@",[[arraySelect objectAtIndex:indexPath.row] objectForKey:FIELDDESC]];
    
    [cell setDistanceLabelstr:[NSString stringWithFormat:@"%@",[ModalController  calDistancebetWithLat:[locationUser.strUserLat doubleValue] with:[locationUser.strUserLong doubleValue] with:[[[arraySelect objectAtIndex:indexPath.row ]objectForKey:@"Lat"]doubleValue] with:[[[arraySelect objectAtIndex:indexPath.row ]objectForKey:@"Long"]doubleValue]]]];
    
    [cell setDealLabelstr:[[arraySelect objectAtIndex:indexPath.row] objectForKey:FIELDDEAL]];
    cell.imagePro.placeholderImage=[UIImage imageNamed:@"placeholder.jpg"];
    cell.imagePro.imageURL =[NSURL URLWithString:[NSString stringWithFormat:@"http://acsdev.co.uk/AppServices/%@",[[arraySelect objectAtIndex:indexPath.row]objectForKey:kVenueLogoImage]]];
    
    if([[arraySelect objectAtIndex:indexPath.row]objectForKey:@"DealIcon"])
    {
        cell.imageOfferDeal.image = [UIImage imageNamed:[NSString stringWithFormat:@"Offer Code %@.png",[[arraySelect objectAtIndex:indexPath.row]objectForKey:@"DealIcon"]]];
    }
    else   
    {
        [cell.imageOfferDeal  removeFromSuperview];
    }
    
    //    if([[[arraySelect objectAtIndex:indexPath.row]objectForKey:FIELDIMAGE] isKindOfClass:[NSString class]])
    //    {
    //        [cell setPhotoFromUrl:[NSString stringWithFormat:IMAGEURL,[[arraySelect objectAtIndex:indexPath.row]objectForKey:FIELDIMAGE]]];   
    //    }
    //    else if([[[arraySelect objectAtIndex:indexPath.row]objectForKey:FIELDIMAGE] isKindOfClass:[NSArray class]])
    //        if([[[arraySelect objectAtIndex:indexPath.row]objectForKey:FIELDIMAGE] count]>0)
    //        {
    //            NSLog(@"%@",[[[arraySelect objectAtIndex:indexPath.row]objectForKey:FIELDIMAGE] objectAtIndex:0]);
    //            [cell setPhotoFromUrl:[NSString stringWithFormat:IMAGEURL,[[[arraySelect objectAtIndex:indexPath.row]objectForKey:FIELDIMAGE] objectAtIndex:0]]];
    //        }
    
    
    
    //cell.venueImage.image = [(UIImageView*)[arrayImages objectAtIndex:indexPath.row] image];
    return (UITableViewCell *)cell;
//    return (UITableViewCell *)cell;
	
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{
    DetailsViewController *detailController = [[DetailsViewController    alloc] initWithNibName:@"DetailsViewController_Nw" bundle:nil];
    
    detailController.dictInfo = [[NSMutableDictionary alloc] initWithDictionary:[arraySelect objectAtIndex:indexPath.row]];
    detailController.isFromFav = 0;
    detailController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detailController
                                         animated:YES];
    [detailController release];
}



- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark- Manage SESSION
-(void)assignInitialValue
{
    start=0;
    if([arrayNearBy count] > 10)
        end=10;
    else
        end = [arrayNearBy count];
    
    if(start<10 && end<10)
    {
        [preBtn setEnabled:NO];
        [nxtBtn setEnabled:NO];
    }
    else if(end >= 10)
    {
        [preBtn setEnabled:NO];
        [nxtBtn setEnabled:YES];
    }
    
    [status setText:[NSString stringWithFormat:@"Results %d-%d of %d",start,end,[arrayNearBy count]]];
    
}
-(void)manageSession:(BOOL)forPrevious
{
    if(forPrevious == NO)
    {
        for(int i=start;i<[arrayNearBy count];i++)
        {
            if(i<(start+10))
                end++;
            else if(i == (start+10))
                break;
        }
    }
    else
    {
        int temp=start;
        for(int i=end;i>0;i--)
        {
            if(i>(end-10))
            {
                start--;
            }
            else if(i == (end-10))
            {
                end=temp;
                break;
            }
        }
    }
    if(start<10 && end<10)
    {
        [preBtn setEnabled:NO];
        [nxtBtn setEnabled:NO];
    }
    else if(end >= 10 && start<10)
    {
        [preBtn setEnabled:NO];
        [nxtBtn setEnabled:YES];
    }
    else if(end == [arrayNearBy count])
    {
        [preBtn setEnabled:YES];
        [nxtBtn setEnabled:NO];
    }
    else
    {
        [preBtn setEnabled:YES];
        [nxtBtn setEnabled:YES];
    }
    [status setText:[NSString stringWithFormat:@"Results %d-%d of %d",start,end,[arrayNearBy count]]];
    [tableNearBy reloadData];
}
-(IBAction)clickToNext:(id)sender
{
    if(end < [arrayNearBy count])
    {
        start=end;
        [self manageSession:NO];
    }
}
-(IBAction)clickToPre:(id)sender
{
    if(start>0)
        [self manageSession:YES];
}

#pragma mark -
#pragma mark Data Source Loading / Reloading Methods

- (void)reloadTableViewDataSource{
	
	//  should be calling your tableviews data source model to reload
	//  put here just for demo
	_reloading = YES;
	
}

- (void)doneLoadingTableViewData{
	
	//  model should call this when its done loading
	_reloading = NO;
	[_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:tableNearBy];
	
}


#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{	
	
	[_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	
	[_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
	
}


#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
	
	[self reloadTableViewDataSource];
    
    [self   tableViewSettingWithRad:50];
    //	[self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:3.0];
	
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
	
	return _reloading; // should return if data source model is reloading
	
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
	
	return [NSDate date]; // should return date data source was last changed
	
}

////////Refreshing data code finish here
@end
